//
//  YDHBaseScrollView.m
//  YunDaHome-iOS
//
//  Created by 刘权 on 2019/8/28.
//  Copyright © 2019 YunDa. All rights reserved.
//

#import "YDHBaseScrollView.h"

@interface YDHBaseScrollView()

/// view 数据源
@property (strong, nonatomic)  NSMutableArray *subViewArray;

@end

@implementation YDHBaseScrollView

#pragma mark--THE LIFE CYCLE
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }
    // code
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    self.backgroundColor = [UIColor whiteColor];
    self.pagingEnabled = NO;
    self.directionalLockEnabled = YES;
    self.alwaysBounceVertical = YES;
    self.contentSize = CGSizeMake(0, self.v_h);
    self.canScroll = YES;
    // 默认设置为纵向排列
    self.margin_top = self.margin_left = self.margin_bottom = self.margin_right = 0.0;
    self.direction = YDHBaseScrollViewDirectionVertical;
    
    return self;
}


#pragma mark--公共方法
/// 拼接一个视图
- (void)appendOneItemView:(UIView*)itemView{
    [self appendOneItemView:itemView atIndex:self.subViewArray.count];
}

/// 在某一位置拼接一个视图
- (void)appendOneItemView:(UIView *)itemView atIndex:(NSInteger)index{
    if (!itemView) {
        return;
    }
    if ([self.subViewArray containsObject:itemView]) {
        // 对同一个view，不能重复拼接
        return;
    }
    if (index > self.subViewArray.count) {
        // 当下标大于个数时，拼接在最后
        index = self.subViewArray.count;
    }
    [self.subViewArray insertObject:itemView atIndex:index];
    [self updateAllItemViews];
    [self addSubview:itemView];
}

/// 在某个视图后面的某个位置拼接个视图
- (void)appendOneItemView:(UIView *)itemView frontView:(UIView *)frontView atIndex:(NSInteger)index{
    if(!itemView || !frontView){
        return;
    }
    if ([self.subViewArray containsObject:itemView]) {
        // 对同一个view，不能重复拼接
        return;
    }
    NSInteger behindViewIndex = [self.subViewArray indexOfObject:frontView];
    if (behindViewIndex == NSNotFound) {
        return;
    }
    
    NSInteger itemIndex = behindViewIndex + index;
    [_subViewArray insertObject:itemView atIndex:itemIndex];
    [self updateAllItemViews];
    [self addSubview:itemView];
}

/// 删除一个子视图
- (void)removeOneItemView:(UIView *)itemView{
    for (int i = 0; i < self.subViewArray.count; i++) {
        UIView* view = [self.subViewArray objectAtIndex:i];
        if (view == itemView) {
            [itemView removeFromSuperview];
            [_subViewArray removeObject:itemView];
            [self updateAllItemViews];
            break;
        }
    }
}

/// 删除某个下标的子视图
- (void)removeOnItemViewAtIndex:(NSInteger)index{
    UIView *view = [self.subViewArray j_objectAtIndex:index];
    if (view != nil) {
        [view removeFromSuperview];
        [self.subViewArray removeObject:view];
        [self updateAllItemViews];
    }
}

/// 替换一个子视图
- (void)replaceItemViewAtIndex:(NSInteger)index withItemView:(UIView*)itemView{
    if (self.subViewArray.count) {
        UIView* view = [_subViewArray j_objectAtIndex:index];
        [view removeFromSuperview];
        [self.subViewArray replaceObjectAtIndex:index withObject:itemView];
        [self updateAllItemViews];
        [self addSubview:itemView];
    }
}

/// 删除所有
- (void)removeAllItemViews{
    for (int i=0; i < _subViewArray.count; i++) {
        UIView* view = [_subViewArray objectAtIndex:i];
        if (view) {
            [view removeFromSuperview];
        }
    }
    [_subViewArray removeAllObjects];
    [self updateAllItemViews];
}

#pragma mark--私有方法
// 判断是否存在某个子视图
- (BOOL)hasItemView:(UIView*)item{
    return [self.itemViewsArray indexOfObject:item] != NSNotFound;
}

/// 刷新子视图frame
- (void)updateAllItemViews{
     BOOL isAllItemView = YES;
    for (UIView *view in self.subViewArray) {
        if (!([view isKindOfClass:[YDHBaseItemView class]] || [view isKindOfClass:[YDHBaseScrollView class]])) {
            isAllItemView = NO;
            break;
        }
    }
    if (isAllItemView == YES) {
        [self updateFrameForAllItemViews];
    } else {
        [self updateFrameForOtherItemViews];
    }
}

/// 刷新子视图frame
- (void)updateFrameForAllItemViews{
    EnumArrayBlock block;
    // 横向起始位置
    __block CGFloat lastX = self.margin_left;
    // 纵向起始位置
    __block CGFloat lastY = self.margin_top;
    long itemCount = _subViewArray.count;
    J_WeakSelf(self);
    switch (self.direction) {
        case YDHBaseScrollViewDirectionHorizontal:
        {
            // 横向
            block = ^(YDHBaseItemView *view, NSUInteger index, BOOL *stop) {
                if (index >= itemCount) {
                    *stop = YES;
                }
                view.v_y = 0;
                view.v_x = lastX + view.margin_left;
                
                [view j_fitVerticalCenterInView:weakself];
                
                CGFloat margin = view.margin_left+view.margin_right;
                // 设置间距
                lastX += view.v_w + margin;
            };
        }
            break;
        case YDHBaseScrollViewDirectionVertical:
        {
            // 默认纵向
            block = ^(YDHBaseItemView *view, NSUInteger index, BOOL *stop) {
                if (view.hidden) {
                    return;
                }
                if (index >= itemCount) {
                    *stop = YES;
                }
                
                view.v_x = 0;
                view.v_y = lastY + view.margin_top;
                
                [view j_fitHorizontalCenterInView:weakself];
                
                // 设置间距
                CGFloat margin = view.margin_bottom+view.margin_top;
                lastY += view.v_h + margin;
            };
        }
            break;
        default:
            break;
    }
    
    if (_subViewArray.count) {
        [_subViewArray enumerateObjectsUsingBlock:block];
    }
    [self updateContentSizeWithLast:(self.direction ? lastY + self.margin_bottom : lastX + self.margin_right)];
}

// 更新其他类型的子视图frame
- (void)updateFrameForOtherItemViews{
    EnumArrayBlock block;
    // 横向起始位置
    __block CGFloat lastX = self.margin_left;
    // 纵向起始位置
    __block CGFloat lastY = self.margin_top;
    long itemCount = _subViewArray.count;
    
    J_WeakSelf(self)
    
    switch (self.direction) {
        case YDHBaseScrollViewDirectionHorizontal:
        {
            // 横向
            block = ^(UIView *view, NSUInteger index, BOOL *stop) {
                if (index >= itemCount) {
                    *stop = YES;
                }
                
                view.v_y = 0;
                view.v_x = lastX;
                [view j_fitVerticalCenterInView:weakself];
                
                CGFloat margin = (index == itemCount - 1) ? 0 : weakself.viewSpacing;
                // 设置间距
                lastX += view.v_w + margin;
            };
        }
            break;
        case YDHBaseScrollViewDirectionVertical:
        {
            // 默认纵向
            block = ^(UIView *view, NSUInteger index, BOOL *stop) {
                if (index >= itemCount) {
                    *stop = YES;
                }
                
                view.v_x = 0;
                view.v_y = lastY;
                [view j_fitHorizontalCenterInView:weakself];
                
                // 设置间距
                CGFloat margin = (index == itemCount - 1) ? 0 : weakself.viewSpacing;
                lastY += view.v_h + margin;
            };
        }
            
            break;
        default:
            break;
    }
    if (_subViewArray.count) {
        [_subViewArray enumerateObjectsUsingBlock:block];
    }
    [self updateContentSizeWithLast:(self.direction ? lastY + self.margin_bottom : lastX + self.margin_right)];
}


// 更新contentSize
- (void)updateContentSizeWithLast:(CGFloat)last{
    if (self.direction) {
        // V
        if (self.canScroll == YES) {
            if (last > self.v_h) {
                self.contentSize = CGSizeMake(0, last);
            }
        }else{
            self.canScroll = NO;
            self.v_h = last;
        }
    } else {
        // H
        if (self.canScroll == YES) {
            if (last > self.v_w) {
                self.contentSize = CGSizeMake(last, 0);
            }
        }else{
            self.canScroll = NO;
            self.v_w = last;
        }
    }
}

/// scrollview截长图
- (UIImage *)snapshot{
    CGRect oldFrame = self.layer.frame;
    CGSize longSize = CGSizeMake(CGRectGetWidth(self.frame), self.contentSize.height);
    UIGraphicsBeginImageContextWithOptions(longSize, NO, [UIScreen mainScreen].scale);
    // 这里需要你修改下layer的frame,不然只会截出在屏幕显示的部分
    self.layer.frame = CGRectMake(0, 0, longSize.width, longSize.height);
    UIImage *image = [UIImage qmui_imageWithSize:longSize opaque:NO scale:0 actions:^(CGContextRef contextRef) {
        [self.layer renderInContext:contextRef];
    }];
    self.layer.frame = oldFrame;
    return image;
}

#pragma mark--GETTER
- (CGFloat)viewSpacing{
    if (!_viewSpacing) {
        _viewSpacing = 0.0;
    }
    return _viewSpacing;
}

- (NSArray *)itemViewsArray{
    return [self.subViewArray copy];
}

- (NSMutableArray *)subViewArray{
    if (!_subViewArray) {
        _subViewArray = [NSMutableArray array];
    }
    return _subViewArray;
}

@end
